<template>
  <div>
    <el-container class="search-container">
      <el-input
          v-model="searchTxt"
          type="text"
          placeholder="输入用户名搜索"
          size="default"
          style="width: 15%; margin-right: 10px"
          @change="search"
          clearable
      ></el-input>
      <el-button @click="search" size="default" type="primary" :disabled="searchTxt.trim().length===0">搜索</el-button>
      <el-button @click="dialogFormVisible = true;currentOp=1" size="default" type="primary">新增用户</el-button>
    </el-container>

    <el-table
        :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)"
        stripe
        height="450"
        style="width: 100%">
      <el-table-column
          prop="uid"
          label="用户名ID"
          :width="100">
      </el-table-column>
      <el-table-column
          prop="username"
          label="用户名"
          :width="150">
      </el-table-column>
      <el-table-column
          prop="password"
          label="密码"
          :width="300"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="phoneNumber"
          label="手机号"
          :width="150"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="province"
          label="所在省市"
          :width="150"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="registerDate"
          label="注册时间"
          :width="200"
          align="center"
      >
      </el-table-column>
      <el-table-column property="edit" label="修改" align="center">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="getUserInfo(scope.$index, scope.row)"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
      <el-table-column property="delete" label="删除" align="center">
        <template #default="scope">
          <el-button
              size="small"
              type="danger"
              @click="deleteUserInfo(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background layout="prev, pager, next"
        style="width:50%; margin-left: 35%; margin-top: 5px"
        :total="totalInfo"
        v-model:page-size="pageSize"
        v-model:current-page="currentPage"
    />
    <el-dialog v-model="dialogFormVisible" title="用户信息表" width="500" >
      <el-form :model="form"
               ref="ruleFormRef"
               status-icon
               :rules="rules"
               :label-position="'right'"
               style="width: 80%;margin: 0 auto"
      >
        <el-form-item label="用户名" label-width="100px" prop="username">
          <el-input v-model="form.username" minlength="1"/>
        </el-form-item>
        <el-form-item label="密码" label-width="100px" prop="password">
          <el-input v-model="form.password" type="password"/>
        </el-form-item>
        <el-form-item label="手机号" label-width="100px" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" minlength="11" maxlength="11"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible=false">取消</el-button>
          <el-button type="primary" @click="formConfirm(ruleFormRef)">确认</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {onBeforeMount, ref} from "vue";
import request from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";
import md5 from "js-md5";
//搜索框文字
let searchTxt=ref('')
//表单规则
const rules = ref({
  username:[
    {min: 1, max: 16, message: '用户名长度为1~16', trigger: 'blur' },
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  password:[
    {min: 6, max: 16, message: '密码长度为6~16', trigger: 'blur' },
    {required: true, message: '密码不能为空', trigger: 'blur' }
  ],
  phoneNumber:[
    {min: 11, max: 11, message: '手机号码为11位', trigger: 'blur' },
    { required: true, message: '手机号不能为空', trigger: 'blur' }
  ]
})
//表单实例
const ruleFormRef = ref()
//表格数据
let tableData=ref([])
//暂存数据，用于搜索
let tempData=ref([])
//用户信息表是否显示
let dialogFormVisible=ref(false)
//用户信息表绑定数据
let form = ref({
  username: '',
  password: '',
  phoneNumber: '',
})
let currentId=0//存放当前编辑的用户id
let currentOp=1//1表示增加用户，2表示编辑用户信息
//分页数据
let totalInfo = ref(100)
let pageSize = ref(10)
let currentPage = ref(1)
onBeforeMount(()=>{
  {
    request.get('http://localhost:8090/admin/getAllUser')
        .then((res)=>{
          tableData.value = res.data.data;
          totalInfo.value = tableData.value.length
          tempData.value = tableData.value
        })
        .catch((err)=>{
          console.log(err)
        })
  }
})

//提交表单确认,新增用户功能或者编辑用户信息
function formConfirm(formEl){
  if (!formEl) return
  formEl.validate((valid, fields) =>{
    if(valid){
      dialogFormVisible.value = false
      if(currentOp===1){
        addUser()
      }
      else {
        editUserInfo(currentId)
      }
    }
  })
}
//搜索
function search(){
  if(searchTxt.value.trim().length===0) {
    tableData.value=tempData.value
    return;
  }

  tableData.value=tableData.value.filter((user)=>{
    return user.username.includes(searchTxt.value);
  })
}
//获取时间字符串
function getDateString(){
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let Hours = date.getHours();
  let Minutes = date.getMinutes();
  let Seconds = date.getSeconds();
  if (month < 10) {
    month = "0" + month;
  }
  if (day < 10) {
    day = "0" + day;
  }
  return year + '-' + month + '-' + day + ' ' + Hours + ':' + Minutes + ':' + Seconds;

}
//用户数据回显
function getUserInfo(index, row){
  currentId=row.uid
  currentOp=2
  dialogFormVisible.value=true
  //获取用户信息
  request.get('http://localhost:8090/admin/getUserByUid',{
    params:{uid:row.uid},
  })
      .then(res=>{
        console.log(res)
        form.value=res.data.data
        form.value.password=''
      })
      .catch(err=>{
        console.log(err)
      })
}
//提交编辑表单的数据
function editUserInfo(uid){
  let formData = new FormData()
  formData.append("uid",uid)
  formData.append("username",form.value.username)
  formData.append("password",md5(form.value.password))
  formData.append("phoneNumber",form.value.phoneNumber)
  request.post("http://localhost:8090/admin/updateUserByUid",formData,{
    "Content-Type": "multipart/form-data;charset=utf-8"
  })
      .then((res)=>{
        if(res.data.code === 200){
          tableData.value = res.data.data;
          tempData.value = tableData.value

          form.value.username=''
          form.value.phoneNumber=''
          form.value.password=''
          ElMessage({
            type: 'success',
            message: '修改成功',
          })
        }
        else{
          ElMessage({
            type: 'error',
            message: res.data.msg,
          })
        }

      })
      .catch((err)=>{
        ElMessage({
          type: 'error',
          message: '修改失败',
        })
      })

}
//删除用户信息
function deleteUserInfo(index, row) {
  ElMessageBox.confirm(
      '您确定要删除用户信息吗？',
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        let formData = new FormData()
        formData.append("uid",row.uid)
        request.post("http://localhost:8090/admin/deleteUserByUid",formData,{
          headers: {'Content-Type': "multipart/form-data, charset=UTF-8"}
        })
            .then(res => {
              if(res.data.code===200){
                tableData.value = res.data.data;
                totalInfo.value  = tableData.value.length
                tempData.value = tableData.value
                ElMessage({
                  type: 'success',
                  message: '删除成功',
                })
              }
              else{
                ElMessage({
                  type: 'error',
                  message: '删除失败',
                })
              }

            })
            .catch(err => {

            })

      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })

}
//新增用户
function addUser(){
  const user={
    username:form.value.username,
    password:md5(form.value.password),
    phoneNumber:form.value.phoneNumber,
    registerDate:getDateString()
  }

  request.post("http://localhost:8090/admin/addUser",user)
      .then(res=>{
        if(res.data.code===200){
          tableData.value=res.data.data
          tempData.value=tableData.value

          form.value.username=''
          form.value.phoneNumber=''
          form.value.password=''

          ElMessage({
            type: 'success',
            message: '添加成功',
          })
        }
        else{
          ElMessage({
            type: 'error',
            message: res.data.msg,
          })
        }
      })
      .catch(err=>{
        console.log(err)
      })
}

</script>

<style scoped>
.search-container {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  margin-bottom: 5px;
}
</style>
